# filepath: d:\CompanyProject\Gitee\DBCompareX\backend\app\models\task_data_sync\export_service.py
"""
数据导出服务模块，负责处理数据导出功能
"""
from typing import List, Dict, Any, Tuple
from bson import ObjectId
import logging

from ...database.mongodb import (
    task_target_list_collection,
    task_source_list_collection,
    task_ts_contrast_result_collection
)

from .data_utils import DataUtils

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ExportService:
    """数据导出服务，提供查询和导出功能"""
    
    target_list_collection = task_target_list_collection
    source_list_collection = task_source_list_collection
    contrast_result_collection = task_ts_contrast_result_collection
    
    @classmethod
    async def get_export_data(cls, execution_log_id: str) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]:
        """
        获取导出数据
        
        Args:
            execution_log_id: 执行日志ID
            
        Returns:
            元组(目标数据, 源数据, 对比结果)
        """
        # 查询目标数据
        target_cursor = cls.target_list_collection.find({
            "task_data_sync_execution_log_id": execution_log_id
        })
        target_data = await target_cursor.to_list(length=None)
        
        # 转换ObjectId为字符串
        for item in target_data:
            item["_id"] = str(item["_id"])
        
        # 查询源数据
        source_cursor = cls.source_list_collection.find({
            "task_data_sync_execution_log_id": execution_log_id
        })
        source_data = await source_cursor.to_list(length=None)
        
        # 转换ObjectId为字符串
        for item in source_data:
            item["_id"] = str(item["_id"])
        
        # 查询对比结果
        contrast_cursor = cls.contrast_result_collection.find({
            "task_data_sync_execution_log_id": execution_log_id,
            "is_same": False
        })
        contrast_results = await contrast_cursor.to_list(length=None)
        
        # 转换ObjectId为字符串
        for result in contrast_results:
            result["_id"] = str(result["_id"])
        
        return target_data, source_data, contrast_results
    
    @classmethod
    async def query_contrast_results(cls, execution_log_id: str) -> List[Dict[str, Any]]:
        """
        查询对比结果
        
        Args:
            execution_log_id: 执行日志ID
            
        Returns:
            对比结果列表
        """
        # 查询记录
        cursor = cls.contrast_result_collection.find({
            "task_data_sync_execution_log_id": execution_log_id
        })
        results = await cursor.to_list(length=None)
        
        # 转换ObjectId为字符串
        for result in results:
            result["_id"] = str(result["_id"])
            
        return results

    @classmethod
    async def get_paired_comparison_data(cls, execution_log_id: str, offset: int = 0, limit: int = 100) -> Dict[str, Any]:
        """
        获取配对的对比数据，支持分页
        
        Args:
            execution_log_id: 执行日志ID
            offset: 跳过的记录数
            limit: 返回的记录数限制
            
        Returns:
            包含配对目标和源数据的字典 {"target": [...], "source": [...], "different_fields": [...]}
        """
        # 查询目标数据，使用limit和skip实现分页
        target_cursor = cls.target_list_collection.find({
            "task_data_sync_execution_log_id": execution_log_id
        }).skip(offset).limit(limit)
        
        target_data = await target_cursor.to_list(length=limit)
        
        # 获取目标数据的ID列表
        target_ids = [str(item["_id"]) for item in target_data]
        
        # 查询对应目标ID的源数据
        source_cursor = cls.source_list_collection.find({
            "task_data_sync_execution_log_id": execution_log_id,
            "task_target_list_id": {"$in": target_ids}
        })
        source_data = await source_cursor.to_list(length=None)
        
        # 查询不匹配的数据项
        different_fields_cursor = cls.contrast_result_collection.find({
            "task_data_sync_execution_log_id": execution_log_id,
            "task_target_list_id": {"$in": target_ids},
            "is_same": False
        })
        different_fields = await different_fields_cursor.to_list(length=None)
        
        # 转换ObjectId为字符串
        for item in target_data:
            item["_id"] = str(item["_id"])
            
        for item in source_data:
            item["_id"] = str(item["_id"])
            item["task_target_list_id"] = str(item["task_target_list_id"])
            
        for item in different_fields:
            item["_id"] = str(item["_id"])
            item["task_target_list_id"] = str(item["task_target_list_id"])
            item["task_source_list_id"] = str(item["task_source_list_id"])
            
        # 查询总记录数
        total_count = await cls.target_list_collection.count_documents({
            "task_data_sync_execution_log_id": execution_log_id
        })
            
        return {
            "target": target_data,
            "source": source_data,
            "different_fields": different_fields,
            "total": total_count,
            "has_more": total_count > (offset + limit)
        }